<template>
  <div class="fx-count-scroll">
    <template v-for="(item,index) in currentCountList" :key="index">
      <fx-count-scroll-item :count="item" :path="scrollPath" :height="height"/>
      <span v-if="(currentCountList.length-1-index)%3===0&&index!==(currentCountList.length-1)">,</span>
    </template>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onBeforeUnmount, onMounted, PropType, ref, watch } from 'vue'
import FxCountScrollItem from './countScrollItem.vue'

interface CountScrollProps {
  count: number;
  start: number;
  height: string;
}

export type CountScrollPath = 'scroll-up' | 'scroll-down'

export default defineComponent({
  name: 'fxCountScroll',
  components: { FxCountScrollItem },
  props: {
    // 初始值
    count: {
      type: Number as PropType<number>,
      default: 0
    },
    // 开始值
    start: {
      type: Number as PropType<number>,
      default: null
    },
    // 高度
    height: {
      type: String as PropType<string>,
      default: '22px'
    }
  },
  setup (props: CountScrollProps) {
    // 初始化当前数字数组
    const currentCountList = computed(() => {
      return String(currentValue.value).split('').map((item: string) => Number(item))
    })
    // 当前值
    const currentValue = ref<number>(props.count)
    // 定时器
    const timer = ref<ReturnType<typeof setInterval> | undefined>(undefined)
    // 滚动方向
    const scrollPath = ref<CountScrollPath>('scroll-up')
    watch(() => props.count, (val: number, old: number) => {
      currentValue.value = val
      scrollPath.value = old > val ? 'scroll-up' : 'scroll-down'
    })
    // 初始化时 计算跑动
    const initCountScroll = () => {
      if (!Number.isInteger(props.start)) return
      currentValue.value = props.start
      timer.value && clearInterval(timer.value)
      timer.value = setInterval(() => {
        const path = props.start > props.count
        if (path) {
          currentValue.value -= 1
          scrollPath.value = 'scroll-down'
          if (currentValue.value <= props.count) {
            currentValue.value = props.count
            timer.value && clearInterval(timer.value)
          }
        } else {
          currentValue.value += 1
          scrollPath.value = 'scroll-up'
          if (currentValue.value >= props.count) {
            currentValue.value = props.count
            timer.value && clearInterval(timer.value)
          }
        }
      }, 100)
    }

    onBeforeUnmount(() => {
      timer.value && clearInterval(timer.value)
    })

    onMounted(() => {
      initCountScroll()
    })

    return {
      scrollPath,
      currentValue,
      currentCountList
    }
  }
})
</script>
